package com.taoyibao.hongcanting.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.event.EventWXPay;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;


public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXPayEntryActivity";

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wx_pay_entry);

        api = WXAPIFactory.createWXAPI(this, CodeConstant.WXPAY_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        LogUtils.dNormal(TAG, "onPayFinish, errCode = " + resp.errCode);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if (resp.errCode == -2) {//用户取消支付操作
                ToastUtils.showToast(CodeUtils.getIdString(R.string.WXPay_cancel));
                finish();
            } else {
                sendPayResult(resp);
            }
        }
    }

    /**
     * 发送支付结果的消息
     */
    public void sendPayResult(BaseResp baseResp) {
        EventWXPay eventWXPay = new EventWXPay();
        eventWXPay.errCode = baseResp.errCode;
        eventWXPay.errStr = baseResp.errStr;
        eventWXPay.type = ((PayResp) baseResp).extData;
        EventBus.getDefault().post(eventWXPay);
        LogUtils.dNormal(TAG,"发送消息");
        finish();
    }
}